import { LINK_LOGIN } from '@/router/constants';
import { useUserStoreWithOut } from '@/store/modules/user';
import { changePw } from '@/views/user/apis';
import { pageCfg } from '@/views/user/config';
import { useErrorMess } from '@/views/user/use';
import { useRouterHelper } from 'vc/src/router';
import message from 'vc/src/common/message';

export function useSubmit() {
  const loading = ref(false);
  const userStore = useUserStoreWithOut();

  const { go } = useRouterHelper();
  // 错误信息存储
  const errMess = reactive({
    pwd: '',
    code: '',
    account: ''
  });

  const { cleanMess, handleError } = useErrorMess(errMess);

  const handleClick = async (formEl, params, loginType?, callback?, isForgot?, isInnerPage?) => {
    if (!formEl) return;

    await formEl.validate(async (valid) => {
      if (valid) {
        cleanMess();
        loading.value = true;

        if (isForgot) {
          await changePw(params)
            .then((res) => {
              if (res.code === 200) {
                if (isInnerPage) {
                  message.success('修改成功');
                } else {
                  message.success({
                    message: pageCfg.goLoginText,
                    duration: 2000
                  });
                  setTimeout(() => {
                    go(LINK_LOGIN, true);
                  }, 1000);
                }
              } else {
                handleError(res);
              }
            })
            .catch((error) => {
              handleError(error);
            })
            .finally(() => {
              loading.value = false;
            });
        } else {
          await userStore
            .loginOrReg(params, loginType)
            .catch((error) => {
              handleError(error);
              callback?.();
            })
            .finally(() => {
              loading.value = false;
            });
        }
      }
    });
  };

  return {
    loading,
    errMess,
    handleClick
  };
}
